from datetime import datetime
from app import db

class Answer(db.Model):
    __tablename__ = 'answers'
    
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    
    # 关系
    likes = db.relationship('Like', backref='answer', lazy='dynamic', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Answer {self.id}>'
    
    def is_liked_by(self, user):
        """检查指定用户是否已点赞此回答"""
        return self.likes.filter_by(user_id=user.id).first() is not None
    
    def to_dict(self):
        """将回答转换为字典表示，用于API响应"""
        return {
            'id': self.id,
            'content': self.content,
            'create_time': self.create_time,
            'update_time': self.update_time,
            'question_id': self.question_id,
            'user_id': self.user_id,
            'likes_count': self.likes.count()
        }

class Like(db.Model):
    __tablename__ = 'likes'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
    answer_id = db.Column(db.Integer, db.ForeignKey('answers.id'), index=True)
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 确保一个用户只能对一个回答点一次赞
    __table_args__ = (db.UniqueConstraint('user_id', 'answer_id', name='unique_user_answer'),) 